﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Runtime.InteropServices;
using System.Windows;
using Microsoft.Xna.Framework.Graphics;

namespace Pavilion.DesignerTool
{
    public class XnaImageRenderer : Render
    {
        public WriteableBitmap WriteableBitmap { get; private set; }

        public void ValidateBitmap(Texture2D texture)
        {
            if (WriteableBitmap == null || WriteableBitmap.Width != texture.Width || WriteableBitmap.Height != texture.Height)
                WriteableBitmap = new WriteableBitmap(texture.Width, texture.Height, 96, 96, PixelFormats.Bgra32, null);
        }

        /// <summary>
        /// WPF only accepts BGRA for the 32 bit pixel format. Thus for each pixel we have to swap the B and R bytes.
        /// </summary>
        private void ConvertRgbaToBgra(byte[] buffer)
        {
            for (int i = 0; i < buffer.Length - 2; i += 4)
            {
                byte rByte = buffer[i];
 
                buffer[i] = buffer[i + 2];
                buffer[i + 2] = rByte;
            }
        }

        public void RenderTextureToBitmap()
        {
            RenderTextureToBitmap(base.Texture);
        }

        public void RenderTextureToBitmap(Texture2D texture)
        {
            ValidateBitmap(texture);

            byte[] buffer = new byte[texture.Width * texture.Height * 4];

            texture.GetData(buffer);
            ConvertRgbaToBgra(buffer);//NOTE: This takes up the most time!!!

            WriteableBitmap.Lock();

            Marshal.Copy(buffer, 0, WriteableBitmap.BackBuffer, buffer.Length);
            WriteableBitmap.AddDirtyRect(new Int32Rect(0, 0, texture.Width, texture.Height));

            WriteableBitmap.Unlock();
        }
    }
}
